package user

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/go-pay/gopay"
	"github.com/go-pay/gopay/pkg/xlog"
	"github.com/go-pay/gopay/wechat/v3"
	"gorm.io/gorm"
	"net/http"
	"time"
	"zhuandan/utils"
	//"time"
	"zhuandan/data_source"
	"zhuandan/models"
)

// 微信支付
func Wechatpayv3(ctx *gin.Context) {
	request := PayBody{}
	ctx.ShouldBind(&request)

	//id := request.ID
	uid := request.Uid
	price := request.Price
	//var pkg models.Buypackage
	//data_source.Db.Where("id = ?", id).First(&pkg)
	var user models.User
	data_source.Db.Where("id = ?", uid).First(&user)
	//if user.Guanlian == 1 {
	//	ctx.JSON(http.StatusOK, gin.H{
	//		"code":    300,
	//		"error":   1,
	//		"success": 400,
	//		"data":    "on",
	//		"msg":     "未关注业务岛",
	//	})
	//	return
	//}
	var buyp models.Buypackage
	data_source.Db.Where("price = ?", price).First(&buyp)
	title := "充值金额：" + utils.FloatToStr64(price)
	var price1 float64
	price1 = price
	if buyp.ID > 0 {
		price1 = price + buyp.Songprice
		title = buyp.Title
	}

	orderno := Generate(time.Time{})

	orderadd := models.Buyorder{
		Uid:     uid,
		Addtime: time.Now().Unix(),
		Status:  1,
		Orderno: orderno,
		Price:   price1,
		Title:   title,
	}
	data_source.Db.Create(&orderadd)
	money1 := price * 10
	money2 := int(money1 * 10)
	if uid == 10590 {
		money2 = 1
	}

	client, err := wechat.NewClientV3(mchId, mchCertificateSerialNumber, mchAPIv3Key, mchPrivateKey)
	if err != nil {
		xlog.Error(err)
		return
	}
	err = client.AutoVerifySign()
	if err != nil {
		xlog.Error(err)
		return
	}
	expire := time.Now().Add(10 * time.Minute).Format(time.RFC3339)
	// 初始化 BodyMap
	bm := make(gopay.BodyMap)
	bm.Set("appid", appId).
		Set("mchid", mchId).
		Set("description", "充值余额").
		Set("out_trade_no", orderno).
		Set("time_expire", expire).
		Set("notify_url", pturl+"/user/wechatNotifyw3").
		SetBodyMap("amount", func(bm gopay.BodyMap) {
			bm.Set("total", money2).
				Set("currency", "CNY")
		}).
		SetBodyMap("payer", func(bm gopay.BodyMap) {
			bm.Set("openid", user.RoutineOpenid)
		})

	wxRsp, err := client.V3TransactionJsapi(ctx, bm)
	jsapi, err := client.PaySignOfJSAPI(appId, wxRsp.Response.PrepayId)
	if err != nil {
		xlog.Error(err)
		return
	}
	fmt.Print(wxRsp)
	fmt.Print(jsapi)
	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"msg":     "ok",
		"error":   0,
		"success": 200,
		"data":    jsapi,
	})
	return
}

// 微信支付
func Wechatpayvywd(ctx *gin.Context) {
	request := PayBody{}
	ctx.ShouldBind(&request)

	uid := request.Uid
	price := request.Price
	var user models.User
	data_source.Db.Where("id = ?", uid).First(&user)
	var buyp models.Buypackage
	data_source.Db.Where("price = ?", price).First(&buyp)
	title := "充值金额：" + utils.FloatToStr64(price)
	var price1 float64
	price1 = price
	if buyp.ID > 0 {
		price1 = price + buyp.Songprice
		title = buyp.Title
	}

	orderno := Generate(time.Time{})

	orderadd := models.Buyorder{
		Uid:     uid,
		Addtime: time.Now().Unix(),
		Status:  1,
		Orderno: orderno,
		Price:   price1,
		Title:   title,
	}
	data_source.Db.Create(&orderadd)
	money1 := price * 10
	money2 := int(money1 * 10)
	if uid == 157030 || uid == 26280 {
		money2 = 1
	}

	client, err := wechat.NewClientV3(mchIdywd, mchCertificateSerialNumberywd, mchAPIv3Key, mchPrivateKeyywd)
	fmt.Println(client)
	if err != nil {
		xlog.Error(err)
		return
	}
	err = client.AutoVerifySign()
	if err != nil {
		xlog.Error(err)
		return
	}
	expire := time.Now().Add(10 * time.Minute).Format(time.RFC3339)
	// 初始化 BodyMap
	bm := make(gopay.BodyMap)
	bm.Set("appid", appidywd).
		Set("mchid", mchIdywd).
		Set("description", "充值余额").
		Set("out_trade_no", orderno).
		Set("time_expire", expire).
		Set("notify_url", pturl+"/user/wechatNotifyw3").
		SetBodyMap("amount", func(bm gopay.BodyMap) {
			bm.Set("total", money2).
				Set("currency", "CNY")
		}).
		SetBodyMap("payer", func(bm gopay.BodyMap) {
			bm.Set("openid", user.Ywdgzheopenid)
		})

	wxRsp, err := client.V3TransactionJsapi(ctx, bm)
	jsapi, err := client.PaySignOfJSAPI(appidywd, wxRsp.Response.PrepayId)
	if err != nil {
		xlog.Error(err)
		return
	}
	fmt.Print(wxRsp)
	fmt.Print(jsapi)
	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"msg":     "ok",
		"error":   0,
		"success": 200,
		"data":    jsapi,
	})
	return
}
func WechatNotifyw3(c *gin.Context) {

	fmt.Println(c.Request)
	notifyReq, err := wechat.V3ParseNotify(c.Request)
	fmt.Println("notifyReq", notifyReq)
	if err != nil {
		xlog.Error(err)
		return
	}
	result, err := notifyReq.DecryptCipherText(mchAPIv3Key)
	fmt.Println("result.TradeState", result.TradeState)
	fmt.Println("result.TradeState", result.OutTradeNo)
	if result.TradeState == "SUCCESS" { // 验证成功
		//fmt.Println(notifyRsp["out_trade_no"].(string))
		Zhifupay(result.OutTradeNo)
		c.String(200, "success")
		return
	}
	c.String(200, "error")
	return
}

// 支付完成
func Zhifupayw3(order string) {
	var orders models.Buyorder
	data_source.Db.Where("orderno = ?", order).First(&orders)
	data_source.Db.Model(&models.Buyorder{}).Where("orderno = ?", order).Update("status", 2)
	addtime := time.Now().Unix()
	log1 := models.Log1{
		Uid:     orders.Uid,
		Addtime: addtime,
		Text:    "修改订单状态成功",
		Orderno: order,
	}
	data_source.Db.Create(&log1)
	var user_info models.User
	data_source.Db.Where("id = ?", orders.Uid).First(&user_info)
	userpricenew := models.Userpricenew{
		Uid:     orders.Uid,
		Addtime: addtime,
		State:   1,
		Price:   orders.Price,
		Title:   "充值余额",
		Dqprice: user_info.Price + orders.Price,
	}
	data_source.Db.Create(&userpricenew)
	data_source.Db.Model(&models.User{}).Where("id = ?", orders.Uid).Update("price", user_info.Price+orders.Price)
	data_source.Db.Model(&models.Buyorder{}).Where("id = ?", orders.ID).Update("daozhang", 2)
	//if user_info.Ywdgzheopenid != "" {

	//
	//	//var weixin models.YwWeixin
	//	//data_source.OtherDb.Where("unionid = ?", user_info.Unionid).First(&weixin)
	//	//data_source.OtherDb.Model(&models.YwWeixin{}).Where("unionid = ?", user_info.Unionid).Update("money", weixin.Money+orders.Price)
	//	//
	//	//account_money := models.YwAccountMoney{
	//	//	AccountId:   weixin.ID,
	//	//	Money:       orders.Price,
	//	//	RemainMoney: weixin.Money + orders.Price,
	//	//	Ctime:       addtime,
	//	//	Memo:        "微信支付充值",
	//	//	Type:        1,
	//	//}
	//	//data_source.OtherDb.Create(&account_money)
	//data := Appaccountuser(user_info.Unionid)
	//log2 := models.Log1{
	//	Uid:     orders.Uid,
	//	Addtime: time.Now().Unix(),
	//	Text:    "查询转单宝用户信息：" + data.User.AccountId,
	//	Orderno: order,
	//}
	//var log []models.Log1
	//log = append(log, log1)
	//log = append(log, log2)
	//data_source.Db.Create(&log)
	//title := "用户充值余额"
	//if orders.Title != "" {
	//	title = orders.Title
	//}
	//if data.User.AccountId != "" {
	//	r := Appaccountmoney(user_info.Unionid, title, "1", orders.Price)
	//	if r.Status == 1 {
	//		price := utils.StrToFloat64(data.User.Money) + orders.Price
	//		data_source.Db.Model(&models.User{}).Where("id = ?", orders.Uid).Update("price", price)
	//		data_source.Db.Model(&models.Buyorder{}).Where("id = ?", orders.ID).Update("daozhang", 2)
	//		userpricenew := models.Userpricenew{
	//			Uid:     orders.Uid,
	//			Addtime: time.Now().Unix(),
	//			State:   1,
	//			Price:   orders.Price,
	//			Title:   "充值余额",
	//			Dqprice: user_info.Price + orders.Price,
	//		}
	//		data_source.Db.Create(&userpricenew)
	//	}
	//}
	//}

}

type ZhifupaywceshiBody struct {
	Orderno string `json:"orderno" from:"orderno"`
}

// 微信支付
func Zhifupaywceshi(ctx *gin.Context) {
	request := ZhifupaywceshiBody{}
	ctx.ShouldBind(&request)
	orderno := request.Orderno

	var orders models.Buyorder
	data_source.Db.Where("orderno = ?", orderno).First(&orders)
	var user_info models.User
	data_source.Db.Where("id = ?", orders.Uid).First(&user_info)

	data := Appaccountuser(user_info.Unionid)

	title := "用户充值余额"
	if orders.Title != "" {
		title = orders.Title
	}
	if data.User.AccountId != "" {
		price := utils.StrToFloat64(data.User.Money) + orders.Price
		data_source.Db.Model(&models.User{}).Where("id = ?", orders.Uid).Update("price", price)
		Appaccountmoney(user_info.Unionid, title, "1", orders.Price)
	} else {
		data_source.Db.Model(&models.User{}).Where("id = ?", orders.Uid).UpdateColumn("price", gorm.Expr("price + ?", orders.Price))
	}
	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"msg":     "ok",
		"error":   0,
		"success": 200,
		"data":    "ok",
	})
	return
}

// 微信支付
func Tuikuanbuchenggong(ctx *gin.Context) {
	var orders []models.Procureorder
	data_source.Db.Where("status = 4").Where("tkdaozhang = 1 or tkdaozhang = 0").Find(&orders)
	//fmt.Println(orders)
	//return
	for _, v := range orders {
		price := v.Price * float64(v.Num)

		var user_info models.User
		data_source.Db.Where("id = ?", v.Uid).First(&user_info)

		data := Appaccountuser(user_info.Unionid)
		//fmt.Println(data)
		userprice := utils.StrToFloat64(data.User.Money) + price

		r := Appaccountmoney(user_info.Unionid, "退款成功", "1", price)
		if r.Status == 1 {
			data_source.Db.Model(&models.User{}).Where("id = ?", v.Uid).Update("price", userprice)
			data_source.Db.Model(&models.User{}).Where("id = ?", v.Fbuid).UpdateColumn("dsx", gorm.Expr("dsx - ?", price))
			data_source.Db.Model(&models.Procure{}).Where("id = ?", v.Procureid).UpdateColumn("buynum", gorm.Expr("buynum - ?", v.Num))
			data_source.Db.Model(&models.Procureorder{}).Where("id = ?", v.ID).Update("tkdaozhang", 2)

		}
	}

	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"msg":     "ok",
		"error":   0,
		"success": 200,
		"data":    "ok",
	})
	return
}

// 微信支付
func Dingdanchuli(ctx *gin.Context) {
	var orders []models.Procureorder
	data_source.Db.Where("status = 4").Where("tkdaozhang = 2").Find(&orders)
	for _, v := range orders {
		price := v.Price * float64(v.Num)
		var user_info models.User
		data_source.Db.Where("id = ?", v.Uid).First(&user_info)

		data := Appaccountuser(user_info.Unionid)
		//fmt.Println(data)
		userprice := utils.StrToFloat64(data.User.Money) + price

		r := Appaccountmoney(user_info.Unionid, "取消退款", "2", price)
		if r.Status == 1 {
			data_source.Db.Model(&models.User{}).Where("id = ?", v.Uid).Update("price", userprice)
			data_source.Db.Model(&models.User{}).Where("id = ?", v.Fbuid).UpdateColumn("dsx", gorm.Expr("dsx + ?", price))
			data_source.Db.Model(&models.Procure{}).Where("id = ?", v.Procureid).UpdateColumn("buynum", gorm.Expr("buynum + ?", v.Num))
			//data_source.Db.Model(&models.Procureorder{}).Where("id = ?", v.ID).Update("tkdaozhang", 2)
		}

	}

	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"msg":     "ok",
		"error":   0,
		"success": 200,
		"data":    "ok",
	})
	return
}

// 充值没有及时到账处理
func Chongzhibudaozhang(ctx *gin.Context) {
	var buyorder []models.Buyorder
	data_source.Db.Where("status = 2").Where("state = 0").Find(&buyorder)
	for _, v := range buyorder {
		var user_info models.User
		data_source.Db.Where("id = ?", v.Uid).First(&user_info)
		data := Appaccountuser(user_info.Unionid)
		if data.User.AccountId == "" {
			fmt.Println(data)
			continue
		}
		r := Appaccountmoney(user_info.Unionid, "用户充值余额", "1", v.Price)
		fmt.Println(r)
		if r.Status == 1 {
			data_source.Db.Model(&models.User{}).Where("id = ?", v.Uid).UpdateColumn("price", gorm.Expr("price + ?", v.Price))
			data_source.Db.Model(&models.Buyorder{}).Where("id = ?", v.ID).Update("state", 2)
		} else {
			fmt.Println(r)
		}
	}

	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"msg":     "ok",
		"error":   0,
		"success": 200,
		"data":    "ok",
	})
	return
}

// 微信支付
func Wechatpayvcx(ctx *gin.Context) {
	request := ZhifupaywceshiBody{}
	ctx.ShouldBind(&request)
	orderno := request.Orderno

	client, err := wechat.NewClientV3(mchId, mchCertificateSerialNumber, mchAPIv3Key, mchPrivateKey)
	if err != nil {
		xlog.Error(err)
		return
	}
	err = client.AutoVerifySign()
	if err != nil {
		xlog.Error(err)
		return
	}
	wxRsp, err := client.V3TransactionQueryOrder(ctx, 2, orderno)
	//jsapi, err := client.PaySignOfJSAPI(appId, wxRsp.Response.PrepayId)
	//if err != nil {
	//	xlog.Error(err)
	//	return
	//}
	fmt.Print(wxRsp)
	//fmt.Print(jsapi)
	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"msg":     "ok",
		"error":   0,
		"success": 200,
		"data":    wxRsp,
	})
	return
}
